package com.ggb.smartstudy.controller;

import com.ggb.smartstudy.entity.Course;
import com.ggb.smartstudy.entity.Result;
import com.ggb.smartstudy.service.CourseService;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author gefangjie
 */
@RestController
@RequestMapping("/course")
@Validated
public class CourseController {

    private final CourseService courseService;

    public CourseController(CourseService courseService) {
        this.courseService = courseService;
    }

    // 获取所有课程信息
    @GetMapping("/getAll")
    public ResponseEntity<List<Course>> getAllCourses() {
        List<Course> courses = courseService.getAllCourses();
        return ResponseEntity.ok(courses);
    }

    // 通过课程ID获取课程信息
    @GetMapping("/{id}")
    public ResponseEntity<Course> getCourseById(@PathVariable Integer id) {
        Course course = courseService.getCourseById(id);
        if (course != null) {
            return ResponseEntity.ok(course);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 添加新课程
    @PostMapping("/add")
    public ResponseEntity<Course> addCourse(@Valid @RequestBody Course course) {
        courseService.insertCourse(course);
        return ResponseEntity.ok(course);
    }

    // 更新课程信息
    @PutMapping("/{id}")
    public ResponseEntity<Course> updateCourse(@PathVariable Integer id, @Valid @RequestBody Course course) {
        course.setId(id);
        courseService.updateCourse(course);
        return ResponseEntity.ok(course);
    }

    // 删除课程
    @DeleteMapping("/delete/{id}")
    public Result deleteCourse(@PathVariable Integer id) {
        int i = courseService.deleteCourse(id);
        if (i == 0) {
            return Result.error("删除失败！未找到课程！");
        } else {
            return Result.success("删除成功！");
        }
    }
}
